package cn.pomelo.album.commom;

import cn.pomelo.album.config.AlbumConfig;
import cn.pomelo.album.model.Image;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
public class FileUtil {

    /**
     * 上传文件到服务器
     *
     * @param file   需要上传的文件
     * @param userid 上传文件 的用户
     * @return 上传完成的图片对象
     */
    public static Image upload(MultipartFile file, String userid) throws IOException {
        InputStream in = file.getInputStream();
        InputStream tempIn = file.getInputStream();
        String folder = Util.dateName();
        File target = new File(AlbumConfig.getProfile() + Constant.SEP + folder);
        if (!target.exists()) {
            target.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        String name = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        String mimeType = originalFilename.substring(originalFilename.lastIndexOf("."));
        String realName = Util.getName(name);
        String url = AlbumConfig.getProfile() + Constant.SEP + folder + Constant.SEP + realName + mimeType;
        FileOutputStream out = new FileOutputStream(url);
        BufferedImage temp = ImageIO.read(tempIn);
        in.transferTo(out);
        Image image = new Image();
        image.setUserid(userid);
        image.setFileName(file.getOriginalFilename());
        image.setRealName(realName);
        image.setFolder(folder);
        image.setType(mimeType.substring(1));
        image.setUrl(getUrl(url));
        image.setUploadDate(new Date());
        image.setWidth(temp.getWidth());
        image.setHeight((double) temp.getHeight());
        image.setSize(Double.valueOf(String.format("%.1f",file.getSize()/1024.0)));
        return image;
    }

    /**
     * 获取文件的 url ，方便访问
     *
     * @param url 需要获取url的路径
     * @return 当前的 url
     */
    private static String getUrl(String url) {
        if (url == null) {
            return null;
        }
        if (url.length() <= AlbumConfig.getProfile().length()) {
            return null;
        }
        int start = url.indexOf(AlbumConfig.getProfile()) + AlbumConfig.getProfile().length();
        url = url.substring(start);
        return Constant.UPLOAD_FILE_PREFIX + url;
    }

    /**
     * 下载服务器的文件
     *
     * @param response
     * @param file     数据库文件的 url
     */
    public static void download(HttpServletResponse response, String file) throws IOException {
        if (file == null || file.length() == 0) {
            throw new IllegalArgumentException("文件名不合法");
        }
        String profile = AlbumConfig.getProfile();
        String downloadPath = profile + Util.substringAfter(file, Constant.UPLOAD_FILE_PREFIX);
        String downloadName = Util.substringAfter(file, Constant.SEP);
        File download = new File(downloadPath);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        // 下载文件名重新编码
        String encode = URLEncoder.encode(downloadName, StandardCharsets.UTF_8); // 百分号编码工具方法
        encode = encode.replaceAll("\\+", "%20");
        String contentDispositionValue = "attachment; filename=" +
                encode +
                ";" +
                "filename*=" +
                "utf-8''" +
                encode;
        response.setHeader("Content-disposition", contentDispositionValue);
        FileInputStream in = new FileInputStream(download);
        in.transferTo(response.getOutputStream());
        in.close();
    }
}
